import React from 'react';
import InputItem from 'antd-mobile/lib/input-item';
import List from 'antd-mobile/lib/list';
import Picker from 'antd-mobile/lib/picker';
import Toast from 'antd-mobile/lib/toast';
import {
  fetchProvinceListApi,
  fetchCitylistListApi,
  fetchCountyListApi
} from 'shared/api';
import { checkMobile } from 'shared/utils/checkChars';
import formatChars from 'shared/utils/formatChars';
import InvoiceButtonGroup from '../InvoiceButtonGroup';
import {
  addInvoiceApi
} from '../../api';
import './index.less';

export default class SpecialInvoiceForm extends React.PureComponent {
  constructor(props) {
    super(props)

    this.state = {
      provinceList: [],
      citylistList: [],
      countyList: [],
      provinceValue: [props.formData.receiver_province_id],
      cityValue: [props.formData.receiver_city_id],
      countyValue: [],
      formData: {
        invoice_type: 2,
        ...props.formData
      }
    }

    if (props.formData.invoice_id) {
      this.updateForm(props.formData);
    }
  }

  componentDidMount() {
    fetchProvinceListApi().then(({ data }) => {
      const provinceList = data.map((item) => ({ label: item.province, value: item.province_id }));
      this.setState({ provinceList });
    })
  }

  componentWillReceiveProps({ formData }) {
    this.updateForm(formData);
  }

  updateForm(formData) {
    const { receiver_province_id, receiver_city_id, receiver_county_id } = formData;
    this.setState({
      ...formData,
      provinceValue: [receiver_province_id],
    })
    this.handleProvinceChange([receiver_province_id]);
    this.handleCityChange([receiver_city_id]).then(() => {
      this.handleCountyChange([receiver_county_id])
    });
  }

  handleChange = (key, value) => {
    const formData ={...this.state.formData};
    formData[key] = value;
    this.setState({ formData });
  }

  handleBlur = (key, value) => {
    const formData ={...this.state.formData};
    formData[key] = value;
    this.setState({ formData });
  }

  handleSubmit=() => {
    const { formData } = this.state;
    formData.receiver_province_id = this.state.provinceValue[0];
    formData.receiver_city_id = this.state.cityValue[0];
    formData.receiver_county_id = this.state.countyValue[0];
    const { receiver_mobile } = formData;

    if (!checkMobile(receiver_mobile)) {
      Toast.fail('手机号码格式不正确')
      return;
    }

    addInvoiceApi(formData).then((res) => {
      if (res.code === 1000) {
        __self.history.push(this.props.backToLink)
      } else {
        Toast.fail('保存失败，参数错误', 1)
      }
    })
  }

  handleProvinceChange = (value) => {
    this.setState({ provinceValue: value });
    fetchCitylistListApi({ province_id: value[0] }).then(({ data }) => {
      const citylistList = data.map((item) => ({ label: item.city, value: item.city_id }));
      this.setState({ citylistList, countyValue: '' });
    })
  }

  handleCityChange = (value) => {
    this.setState({ cityValue: value });
    return fetchCountyListApi({ city_id: value[0] }).then(({ data }) => {
      const countyList = data.map((item) => ({ label: item.county, value: item.county_id }));
      this.setState({ countyList });
    })
  }

  handleCountyChange = (value) => {
    this.setState({ countyValue: value });
  }


  render() {
    const { provinceList, citylistList, countyList,
      provinceValue, cityValue, countyValue } = this.state;
    const { title, idcode, register_address, register_phone, register_bank,
      register_bank_num, receiver_fullname, receiver_mobile, receiver_address  } = this.state.formData;

    return (
      <div className="special-invoice-form">
        <List className='form-item'>
          <InputItem
            value={title}
            onChange={(value) => { this.handleChange('title', value) }}
            onBlur={(value) => { this.handleBlur('title', formatChars(value)) }}
          >
            <span>单位名称<sup>*</sup></span>
          </InputItem>
          <InputItem
            value={idcode}
            onChange={(value) => {
              value=value.replace(/[^\dA-Z]/g,'')
              this.handleChange('idcode', value)
            }}
          >
            <span>纳税人识别码<sup>*</sup></span>
          </InputItem>
          <InputItem
            value={register_address}
            onChange={(value) => { this.handleChange('register_address', value) }}
            onBlur={(value) => { this.handleBlur('register_address', formatChars(value)) }}
          >
            <span>注册地址<sup>*</sup></span>
          </InputItem>
          <InputItem
            value={register_phone}
            type="number"
            onChange={(value) =>{ this.handleChange('register_phone', value) }}
          >
            <span>注册电话<sup>*</sup></span>
          </InputItem>
          <InputItem
            value={register_bank}
            onChange={(value) => { this.handleChange('register_bank', value) }}
            onBlur={(value) => { this.handleBlur('register_bank', formatChars(value)) }}
          >
            <span>开户银行<sup>*</sup></span>
          </InputItem>
          <InputItem
            value={register_bank_num}
            type="number"
            onChange={(value) =>{ this.handleChange('register_bank_num', value) }}
          >
            <span>银行账户<sup>*</sup></span>
          </InputItem>
          <InputItem
            value={receiver_fullname}
            onChange={(value) => { this.handleChange('receiver_fullname', value) }}
            onBlur={(value) => { this.handleBlur('receiver_fullname', formatChars(value)) }}
          >
            <span>收票人姓名<sup>*</sup></span>
          </InputItem>
          <InputItem
            value={receiver_mobile}
            onChange={(value) =>{ this.handleChange('receiver_mobile', value) }}
          >
            <span>收票人手机<sup>*</sup></span>
          </InputItem>
          <div className="am-list-item am-input-item am-list-item-middle area-select">
            <div className="am-list-line">
              <div className="am-input-label am-input-label-5">
                <span>收票人省份<sup>*</sup></span>
              </div>
              <div className="am-input-control">
                <Picker
                  data={provinceList}
                  cols={1}
                  className="forss"
                  value={provinceValue}
                  onChange={this.handleProvinceChange}
                >
                  <List.Item arrow="horizontal" />
                </Picker>
                <Picker
                  data={citylistList}
                  cols={1}
                  className="forss"
                  value={cityValue}
                  onChange={this.handleCityChange}
                >
                  <List.Item arrow="horizontal" />
                </Picker>
                <Picker
                  data={countyList}
                  cols={1}
                  className="forss"
                  value={countyValue}
                  onChange={this.handleCountyChange}
                >
                  <List.Item arrow="horizontal" />
                </Picker>
              </div>
            </div>
          </div>
          <InputItem
            value={receiver_address}
            onChange={(value) => { this.handleChange('receiver_address', value) }}
            onBlur={(value) => { this.handleBlur('receiver_address', formatChars(value)) }}
          >
            <span>详细地址<sup>*</sup></span>
          </InputItem>
        </List>

        <div className="special-invoice-desc">
          <span>增值税专用发票将在订单完成后开据并邮寄</span>
        </div>

        <InvoiceButtonGroup
          onSubmit={this.handleSubmit}
          backToLink={this.props.backToLink}
        />
      </div>
    )
  }
}